import _ from 'lodash'

export default {
  inheritAttrs: false,
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    size: {
      type: String,
      default: 'medium'
    },
    title: String,
    titleIcon: String,
    buttons: {
      type: Array,
      default() {
        return []
      }
    },
    contentLoading: false,
    clickModalClose: true
  },
  created() {
    this.initButtons()
    this.customClass = `${this.customClass} f-dialog--${this.size}`
  },
  mounted() {},
  watch: {
    buttons() {
      this.initButtons()
    },
    visible(value) {
      this.innerVisible = value
    },
    innerVisible(value) {
      if (!value) {
        this.$emit('update:visible', false)
      } else {
        for (let item of this.buttonList) {
          item.isLoading = false
        }
      }
    }
  },
  data() {
    return {
      buttonList: [],
      innerVisible: this.visible,
      customClass: 'f-dialog'
    }
  },
  methods: {
    initButtons() {
      let buttonList = _.cloneDeep(this.buttons)
      for (let button of buttonList) {
        let type = button.type || ''
        button.plain = type.indexOf('plain') != -1
        if (type.indexOf('danger') != -1) {
          button.type = 'danger'
        } else {
          // 手动undefined指定默认样式
          button.type = undefined
        }
      }
      this.buttonList = buttonList
    },
    handleButtonClick(button) {
      this.$emit('button-click', button.key, () => {
        this.innerVisible = false
      })
      if (button.async) {
        let buttonList = _.cloneDeep(this.buttonList)
        for (let item of buttonList) {
          if (item.key == button.key) {
            item.isLoading = true
          }
        }
        this.buttonList = buttonList
      }
      if (!button.async && !button.manualClose) {
        this.innerVisible = false
      }
    },
    handleDialogOpen() {
      this.$emit('open')
    },
    handleDialogClose() {
      this.$emit('close')
    }
  }
}
